#include "eventlistener.h"
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonValue>
#include <QtCore/QDateTime>

EventListener::EventListener(QObject *parent) :
  QObject(parent)
{
}

Shard EventListener::shard()
{
  return s;
}

void EventListener::setShard(const Shard &s)
{
  this->s = s;
}

void EventListener::init()
{
  timer = new QTimer(this);
  connect(timer, SIGNAL(timeout()), this, SLOT(tick()));

  url = new QUrl("http://chat-" + s.regionURLName() + ".riftgame.com:8080/chatservice/zoneevent/list?shardId=" + QString::number((s.shardTrionId())));
  request = new QNetworkRequest(*url);
  manager = new QNetworkAccessManager;
  connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(parse(QNetworkReply*)));

  tick();
  timer->start(10000);
}

void EventListener::done()
{
  timer->deleteLater();
  delete url;
  delete request;
  manager->deleteLater();
}

void EventListener::tick()
{
  manager->get(*request);
}

void EventListener::parse(QNetworkReply *reply)
{
  if(reply->error() == QNetworkReply::NoError)
    {
      QJsonDocument jsondoc = QJsonDocument::fromJson(reply->readAll());

      if(jsondoc.isObject() && jsondoc.object().value("status").toString() == "success")
        {
          QJsonArray data = jsondoc.object().value("data").toArray();
          QList<Zone> list;
          for(QJsonArray::const_iterator i = data.constBegin(); i != data.constEnd(); i++)
            {
              QJsonObject obj = (*i).toObject();

              Zone z;
              z.setTrionId(obj.value("zoneId").toDouble());
              if(obj.value("name").type() != QJsonValue::Undefined)
                {
                  z.setEventName(obj.value("name").toString());

                  QDateTime date;
                  date.setTime_t((uint) obj.value("started").toDouble());
                  z.setEventTime(QTime(QTime(0,0,0,0).addSecs(date.secsTo(QDateTime::currentDateTimeUtc()))));
                }
              if(!list.contains(z))
                list.append(z);
            }
          qSort(list.begin(), list.end(), qGreater<Zone>());
          emit parsedEventData(list);
        }
    }
  reply->deleteLater();
}
